#include "mat_sparkle.h"
#include "mat_define.h"
#include "mat_logicboard.h"
#include "mat_game.h"
#include "mat_animation_mgr.h"
#include "mat_gamerule.h"

#include "graphics/graphics_util.h"
#include "num/rand.h"


MATSparkle::MATSparkle()
{
	float Scale = (float)GraphicsUtil::WIDTH / (float)TEXTURE_WIDTH;
	for(int i = 0; i < SPARKLE_MAX; i++)
	{
		m_Sparkles[i].m_Sprite.Create("tile_sparkle");
		m_Sparkles[i].m_Sprite.m_Size *= Scale;
		m_Sparkles[i].m_Delay = num::RAND32::Instance().RandFloat(1.0f,4.0f);
	}
	
}

void		MATSparkle::Tick(float dt)
{
	

	for(int i = 0; i < SPARKLE_MAX; i++)
	{
		m_Sparkles[i].Tick(dt);
	}
}
	

void		MATSparkle::Render(const math::Vec2& BoardOffset)
{
	for(int i = 0; i < SPARKLE_MAX; i++)
	{
		m_Sparkles[i].Render(BoardOffset);
	}
}


void		MATSparkle::Sparkle::Render(const math::Vec2& BoardOffset)
{
	if(m_IsShowing)
	{
		m_Sprite.m_Pos = m_Pos + BoardOffset;
		m_Sprite.RenderRotated();
	}
}

void	MATSparkle::ForceFinish()
{
	for(int i = 0; i < SPARKLE_MAX; i++)
	{
		m_Sparkles[i].m_IsShowing = false;
		m_Sparkles[i].m_Sprite.Tick(100);
		m_Sparkles[i].m_Delay = num::RAND32::Instance().RandFloat(2.0f,4.0f);
	}
}



void		MATSparkle::Sparkle::Tick(float dt)
{
	MATGem* BC;
	if(m_IsShowing)
	{
		m_IsShowing = m_Sprite.Tick(dt);
		MATGem* BC = MATLogicBoard::Instance().GetContentAt(m_Y,m_X);
		if(BC && BC->m_IsSmall )
		{
			m_IsShowing = false;
			m_Sprite.Tick(100);
			m_Delay = num::RAND32::Instance().RandFloat(2.0f,4.0f);
		}
	}
	else
	{
		
		m_Delay -= dt;

		if(m_Delay <= 0)
		{
			m_Delay = num::RAND32::Instance().RandFloat(2.0f,4.0f);

			std::vector<int> TempList;
			for(int y = 0; y < MATGameRule::Instance().GetBoardCountY(); y++)
			{
				for(int x = 0; x < MATGameRule::Instance().GetBoardCountX(); x++)
				{
					BC = MATLogicBoard::Instance().GetContentAt(y,x);
					if(BC && BC->m_IsSmall == false && BC->m_IsBomb == false)
					{
						TempList.push_back(y* 10 + x);		// make it single integer
					}
				}
			}

			int Count = (int)TempList.size();
			if(Count <= 0)
				return;
			int RandomIndex = num::RAND32::Instance().RandInt(0, Count - 1);
			m_Y = TempList[RandomIndex] / 10;
			m_X = TempList[RandomIndex] % 10;

			MATAnimation* pAni = MATAnimationManager::Instance().GetActiveAnimAt(m_Y,m_X);
			if(pAni)
				return;

			m_Pos = MATGame::GetBoardPos(m_Y,m_X);
			m_Pos.x += num::RAND32::Instance().RandFloat(-0.024f, 0.024f);
			m_Pos.y += num::RAND32::Instance().RandFloat(-0.024f, 0.024f);

			m_IsShowing = true;
			

			
		}
	}
}